/*
 * JTalkerClientFront.java
 *
 * Created on 27. Oktober 2003, 11:11
 */

package info.chrm.jtalker;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import info.chrm.helper.*;

/**
 *
 * @author  ChrM
 */
public class JTalkerClientFront extends javax.swing.JFrame implements java.awt.event.ActionListener, JTalkerClientCommandInterface {
    
    /** Creates new form JTalkerClientFront */
    public JTalkerClientFront(JTalkerClient _jtc) {
        // Init GUI
        this.initComponents();
	this.setIconImage(new javax.swing.ImageIcon(cl.getResource("icons/jtalker.png")).getImage());

	// Init client
	if(_jtc == null)
	  this.theClient = new JTalkerClient();
	else
	  this.theClient = _jtc;

        this.jLabel1.setText(this.theClient.RELEASE);     // Footer version info

	// Add List model
	this.jListMembers.setCellRenderer(new MyCellRenderer(this));
	this.jListMembers.setModel(this.theClient.memberList);



	MouseListener mouseListener = new MouseAdapter() {
	   public void mouseClicked(MouseEvent e) {
	      if (e.getClickCount() == 2) {
		 //int index = list.locationToIndex(e.getPoint());
	         WriteMessageActionPerformed(null);
	      }
	   }

	   public void mousePressed(MouseEvent e){
            	maybeShowPopup(e);            
	   }
            
	   public void mouseReleased(MouseEvent e){
            	maybeShowPopup(e);
            }
	};
 
	this.jListMembers.addMouseListener(mouseListener);

        // Init Timer for updating the User List
	UpdateTimer ut = new UpdateTimer(this);
	ut.start();

	// Ok, client is ready, lets try to load plugins!
	if(this.loadAllPlugins())
            this.updatePluginShortcuts();

        this.theClient.setFrontend(this);
        this.theClient.registerForCommandResponse(this);
    }

    /** Gets the PluginLoader */
    public JTalkerClientPluginLoader getPluginLoader() {
        return this.myPluginLoader;
    }

    /** Loads all Plugins and generates some extra menus */
    public boolean loadAllPlugins() {
        try {
                // First remove all Submenus        
                this.jMenuPlugins.removeAll();
               
                if(this.myPluginLoader == null) {
                    System.out.println("[PLUGIN]: Loader not exists now - create object");
		    this.myPluginLoader = new JTalkerClientPluginLoader(this);
                } else {
                    // Clear list

                }

                System.out.println("[PLUGIN]: Reload all plugins");
                if(!this.myPluginLoader.initPlugins(this.theClient.pluginDir))
                    return false;

                // Create menus for loaded plugins
                String [] allPlugins = this.myPluginLoader.getPluginClassNames();

                if(allPlugins != null) {
                    for( int i = 0; i < allPlugins.length; i++ ) {                    
                        this.createPluginMenuFor(allPlugins[i]);
                    }
                }

                // Ok, all Plugins added, create Overview MenuItem
                this.jMenuPlugins.addSeparator();
                PlugInMenuItem tmpSettings = new PlugInMenuItem("Overview", 2);
                tmpSettings.setText("Plugin Overview...");
                tmpSettings.addActionListener(this);
                this.jMenuPlugins.add(tmpSettings);
                
	} catch (Exception _e) {
		System.err.println("*** Can't load plugins: " + _e.toString());
		_e.printStackTrace();
                return false;
	}

        return true;
    }

    /** Creates a menu structure for a plugin */
    private boolean createPluginMenuFor(String _class) {
        // Create top menu
        JMenu tmpMenu = new javax.swing.JMenu();
        tmpMenu.setText(this.myPluginLoader.getPluginByClassName(_class).getName());

        // Create Items
        PlugInMenuItem tmpMainGUI = new PlugInMenuItem(_class, 0);
        tmpMainGUI.setText("Open Dialog...");
        tmpMainGUI.addActionListener(this);
        tmpMenu.add(tmpMainGUI);

        PlugInMenuItem tmpSettings = new PlugInMenuItem(_class, 1);
        tmpSettings.setText("Plugin Settings...");
        tmpSettings.addActionListener(this);
        tmpMenu.add(tmpSettings);
        
        this.jMenuPlugins.add(tmpMenu);

        return true;
    }

    /** ActionListener Interface implementaion */
    public void actionPerformed(java.awt.event.ActionEvent _evt) {
        PlugInMenuItem tmpItem = (PlugInMenuItem)_evt.getSource();
        
        if(tmpItem.type == 0)
            this.openPluginMainGUIFor(tmpItem.pluginClass);
        else if(tmpItem.type == 1)
            this.openPluginSettingsGUIFor(tmpItem.pluginClass);
        else if(tmpItem.type == 2) {
            if(this.myPluginsInfoDialog == null)
                this.myPluginsInfoDialog = new JTalkerClientPluginsInfo(this);
                
            if(this.myPluginsInfoDialog.updatePluginList(null))
                this.myPluginsInfoDialog.setVisible(true);
        }
    }

    /** Opens Plugins Main GUI */
    private void openPluginMainGUIFor(String _pluginClassName) {
        System.out.println("Main: " + _pluginClassName);
        this.myPluginLoader.showPluginsGUI(_pluginClassName, 0);
    }

    /** Opens Plugins Settings GUI */
    private void openPluginSettingsGUIFor(String _pluginClassName) {
        System.out.println("Settings: " + _pluginClassName);
        this.myPluginLoader.showPluginsSettings(_pluginClassName, 0);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        jPanelStatus = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanelToolsT = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jButtonConnect = new javax.swing.JButton();
        jToggleButtonStatus = new javax.swing.JToggleButton();
        //jComboBoxRefresh = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButtonConfig = new javax.swing.JButton();
        jPanelToolsR = new javax.swing.JPanel();
        jToolBar2 = new javax.swing.JToolBar();
        jButtonOpen = new javax.swing.JButton();
        jButtonMail = new javax.swing.JButton();
        jButtonReload = new javax.swing.JButton();
        jPanelMamberList = new javax.swing.JPanel();
        jScrollPaneMembers = new javax.swing.JScrollPane();
        jListMembers = new javax.swing.JList();
        jMenuBarMain = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemClose = new javax.swing.JMenuItem();
        jMenuItemSettings = new javax.swing.JMenuItem();
        jMenuServer = new javax.swing.JMenu();
        jMenuItemAccount = new javax.swing.JMenuItem();
        jMenuItemConnect = new javax.swing.JMenuItem();
        jMenuItemCommand = new javax.swing.JMenuItem();
        jMenuItemChatroom = new javax.swing.JMenuItem();
        jMenuItemAbout = new javax.swing.JMenuItem();
        jMenuStatus = new javax.swing.JMenu();
        jMenuPlugins = new javax.swing.JMenu();
        jMenuAbout = new javax.swing.JMenu();
        jCheckBoxMenuItemBusy = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItemBusy.setSelected(false);
	cl = ResourceAnchor.class.getClassLoader();
        connectEncrypted = new ImageIcon(cl.getResource("icons/encrypted.png"));
        connectPlainText = new ImageIcon(cl.getResource("icons/decrypted.png"));
        jPanelPlugIns = new javax.swing.JPanel();

        setTitle("JTalker");
	addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jPanelStatus.setLayout(new java.awt.BorderLayout());

        jLabel1.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanelStatus.add(jLabel1, java.awt.BorderLayout.CENTER);

        jLabel2.setText("Ready");
        jLabel2.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanelStatus.add(jLabel2, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanelStatus, java.awt.BorderLayout.SOUTH);

        jPanelToolsT.setLayout(new java.awt.BorderLayout());

        jToolBar1.setRollover(true);
        //jButtonConnect.setText("Connect");
	jButtonConnect.setIcon(new ImageIcon(cl.getResource("icons/connected.png")));
        jButtonConnect.setToolTipText("Connect/Disconnect");
	jButtonConnect.setMargin(new java.awt.Insets(1, 2, 1, 2));
        jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonConnect);

        //jToggleButtonStatus.setText("Busy");
	jToggleButtonStatus.setIcon(new ImageIcon(cl.getResource("icons/go_busy.png")));
        jToggleButtonStatus.setToolTipText("Set status to busy");
	jToggleButtonStatus.setMargin(new java.awt.Insets(1, 2, 1, 2));
        jToggleButtonStatus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
	       if(jCheckBoxMenuItemBusy.isSelected())
		  jCheckBoxMenuItemBusy.setSelected(false);
	       else
		  jCheckBoxMenuItemBusy.setSelected(true);
                
	       statusActionPerformed(evt);
            }
        });
        jToolBar1.add(jToggleButtonStatus);
        
        //jButton1.setText("Refresh");
	/*jButton1.setIcon(new ImageIcon(cl.getResource("icons/reload.png")));
        jButton1.setToolTipText("Refresh now");
	jButton1.setMargin(new java.awt.Insets(1, 2, 1, 2));
	jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshActionPerformed();
            }
        });
        jToolBar1.add(jButton1);*/

        //jButtonConfig.setText("Config");
	jButtonConfig.setIcon(new ImageIcon(cl.getResource("icons/configure.png")));
        jButtonConfig.setToolTipText("Configure JTalker");
	jButtonConfig.setMargin(new java.awt.Insets(1, 2, 1, 2));
	jButtonConfig.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showSettings();
            }
        });
        jToolBar1.add(jButtonConfig);
        jToolBar1.addSeparator();
        
        this.jPanelPlugIns.setLayout(new java.awt.GridLayout());
        jToolBar1.add(this.jPanelPlugIns);

	//jComboBoxRefresh.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5 sec", "15 sec", "30 sec" }));
        //jComboBoxRefresh.setToolTipText("Refresh intervall");
        //jComboBoxRefresh.setMaximumSize(new java.awt.Dimension(100, 32767));
        //jToolBar1.add(jComboBoxRefresh);

        jPanelToolsT.add(jToolBar1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanelToolsT, java.awt.BorderLayout.NORTH);

        jPanelToolsR.setLayout(new java.awt.BorderLayout());

        jToolBar2.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar2.setRollover(true);
        //jButtonOpen.setText("Open");
	jButtonOpen.setIcon(new ImageIcon(cl.getResource("icons/message_window.png")));
        jButtonOpen.setToolTipText("Open a chat window");
	jButtonOpen.setMargin(new java.awt.Insets(1, 2, 1, 2));
        jButtonOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                WriteMessageActionPerformed(evt);
            }
        });
        jToolBar2.add(jButtonOpen);

	jButtonMail.setIcon(new ImageIcon(cl.getResource("icons/send_mail.png")));
        jButtonMail.setToolTipText("Send a mail to selected users");
	jButtonMail.setMargin(new java.awt.Insets(1, 2, 1, 2));
        jButtonMail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                WriteMailActionPerformed(evt);
            }
        });
        jToolBar2.add(jButtonMail);

        //jButtonReload.setText("Reload");
        //jToolBar2.add(jButtonReload);

        jPanelToolsR.add(jToolBar2, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanelToolsR, java.awt.BorderLayout.EAST);

        jPanelMamberList.setLayout(new java.awt.GridLayout());

        jScrollPaneMembers.setViewportView(jListMembers);

        jPanelMamberList.add(jScrollPaneMembers);

        getContentPane().add(jPanelMamberList, java.awt.BorderLayout.CENTER);

        jMenuFile.setText("Client");
        jMenuItemClose.setText("Exit");
	jMenuItemClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitForm(null);
            }
        });

        jMenuItemSettings.setText("Settings...");
        jMenuItemSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showSettings();
            }
        });

        jMenuFile.add(jMenuItemSettings);
        jMenuFile.addSeparator();
        jMenuFile.add(jMenuItemClose);

        jMenuBarMain.add(jMenuFile);

        jMenuServer.setText("Server");
        jMenuItemAccount.setText("Create Account...");
        jMenuItemAccount.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accountActionPerformed(null);
            }
        });
        jMenuServer.add(jMenuItemAccount);
      

	jMenuItemCommand.setText("Send Command...");
	jMenuItemCommand.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commandActionPerformed(evt);
            }
        });
        jMenuServer.add(jMenuItemCommand);

	jMenuItemChatroom.setText("Create Chatroom...");
	jMenuItemChatroom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chatroomActionPerformed(evt);
            }
        });
        jMenuServer.add(jMenuItemChatroom);

        jMenuServer.addSeparator();

        jMenuItemConnect.setText("Connect/Disconnect");
	jMenuItemConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(null);
            }
        });
        jMenuServer.add(jMenuItemConnect);

        jMenuBarMain.add(jMenuServer);

        jMenuStatus.setText("Status");
        jCheckBoxMenuItemBusy.setText("Busy");
	jCheckBoxMenuItemBusy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
	       if(jToggleButtonStatus.isSelected()) 
		  jToggleButtonStatus.setSelected(false);
	       else 
		  jToggleButtonStatus.setSelected(true);
	       
               	  
	       statusActionPerformed(null);
            }
        });
        jMenuStatus.add(jCheckBoxMenuItemBusy);
        
	jMenuBarMain.add(jMenuStatus);

	// TODO: Plugins
	jMenuPlugins.setText("Plugins");
        jMenuBarMain.add(jMenuPlugins);

	
	jMenuAbout.setText("?");
        jMenuItemAbout.setText("About...");
	jMenuItemAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
	       javax.swing.JOptionPane.showMessageDialog(null, 
						      "JTalker " + JTalkerClient.RELEASE + "\nCopyright (C) 2009 by ChrM (http://www.chrm.info)\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License as\npublished by the Free Software Foundation; either version 2 of\nthe License, or (at your option) any later version.\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.", 
						      "About JTalker", 
						      javax.swing.JOptionPane.INFORMATION_MESSAGE);
            }
        });
        jMenuAbout.add(jMenuItemAbout);

        jMenuBarMain.add(jMenuAbout);

        setJMenuBar(jMenuBarMain);

        pack();
    }//GEN-END:initComponents

    /** Shows the setting dialog */
    private void showSettings() {
       if(this.mySettings == null)
	 this.mySettings = new JTalkerFrontSettings(this);

       this.mySettings.setVisible(true);
    }

    /** Starts a browser with an URL */
    public boolean openBrowser(String _url) {
       String application;

       if(_url.startsWith("mailto:"))
	  application = this.theClient.defaultMailer;
       else
	  application = this.theClient.defaultBrowser;
       
       /*try {
	  java.lang.Runtime.getRuntime().exec(application + " " +  _url);
       } catch (Exception _e) {
		System.err.println("*** Can't execute process: " + _e.toString());
		return false;
       }*/

       return ProcessExecuter.execute(application, _url, true);
    }

    /** Create a command send dialog */
    public void commandActionPerformed(java.awt.event.ActionEvent evt) {
       if(this.myCommandDialog == null)
	  this.myCommandDialog = new JTalkerFrontCommand(this);

       //this.myCommandDialog.show();
       this.myCommandDialog.setVisible(true);
    }
   
    /** Connection to server */
    public void connectActionPerformed(java.awt.event.ActionEvent evt) {
       // Connect or disconnect to server
       if(!this.isConnected) {
	  if(this.theClient.connect()) {
	     if(!this.theClient.savePassword) {
		// Password not saved - get it
		String retVal = JOptionPane.showInputDialog("Input password for \"" + this.theClient.userName + "\"");
		
		if(retVal != null)
		  this.theClient.userPasswd = retVal;
		else {
		  this.theClient.closeConnection();
		  return;
		}
	     }
		
	     this.theClient.loginOnServer();

	     //if(this.theClient.loginOnServer()) {
               /*
	       this.isConnected = true;
	       this.jLabel2.setText("Connected to " + this.theClient.getServerInfo());
               
               if(this.theClient.useSSL) {
                   this.jLabel2.setIcon(this.connectEncrypted);
               } else {
                   this.jLabel2.setIcon(this.connectPlainText);
               }

	       this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("icons/disconnected.png")));
	       this.theClient.memberList.propertyChanged();
	     } else {
		this.jLabel2.setText("Can't log in on server!");
	     }*/
	   } else {
	     this.isConnected = false;
	     this.jLabel2.setText("Can't connect to " + this.theClient.getServerInfo());
	     this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("icons/connected.png")));
	   }
       }
       else {
	  this.theClient.closeConnection();
	  this.jLabel2.setText("You are disconnected now.");
          this.jLabel2.setIcon(null);
	  this.isConnected = false;
	  this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("icons/connected.png")));
       }
    }

    /** Sets needed values on connect/disconnect */
    private void connectionEstablished(boolean _yes) {
        if(_yes) {
           this.isConnected = true;
           this.jLabel2.setText("Connected to " + this.theClient.getServerInfo());
               
           if(this.theClient.useSSL) {
               this.jLabel2.setIcon(this.connectEncrypted);
           } else {
               this.jLabel2.setIcon(this.connectPlainText);
           }

           this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("icons/disconnected.png")));
           this.theClient.memberList.propertyChanged();
        } else {
           this.isConnected = false;
           this.jLabel2.setText("Can't log in on server!");
        }
    }

    /** Creates a new Account on the server */
    private void accountActionPerformed(java.awt.event.ActionEvent evt) {
       new CreateAccountWindow(this, true).setVisible(true);
    }

    /** Creates a new chatroom */
    private void chatroomActionPerformed(java.awt.event.ActionEvent evt) {
       new CreateChatroomWindow(this, true).setVisible(true);
    }

    /** Opens the Chat Window */
    private void WriteMessageActionPerformed(java.awt.event.ActionEvent evt) {
       try {
	  JTalkerClient.MemberData member = this.getSelectedUser();
	  member.showChatWindow(this);
       } catch (Exception _ex) {
	  return;
       }
	  
       //JTalkerFrontChat chatWin = new JTalkerFrontChat(this, member);
       //chatWin.show();
    }

    /** A command answer will be send to us from the server using this method 
     *  @return true, if the _id belongs to our command */
    public boolean setCommandAnswer(String _id, String _from, String _content) {
        // TODO: actions for all answers
        if(_id.equals("rmchat01")) {
            // Answer for remove chatroom!
        } else if(_id.equals("disconnect01")) {
	    this.jLabel2.setText("You are disconnected now.");
            this.jLabel2.setIcon(null);
	    this.isConnected = false;
	    this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("icons/connected.png")));
        }

        return false;
    }

    /** Tries to remove a chatroom */
    public void removeChatroom(String _roomname) {
        if(!this.theClient.isConnected)
	   return;
	
       this.theClient.sendMessage("std::removeChatRoom(\"" + _roomname + "\")", null, "command", null, "rmchat01");
    }

    /** Tries to add a user to a chatroom */
    public void addChatroomUser(String _roomname, String _username) {
       if(!this.theClient.isConnected)
	   return;
	
       this.theClient.sendMessage("std::addChatRoomUser(\"" + _roomname + "\", \"" + _username + ")", null, "command", null, "addchatuser01");
    }

    /** Tries to remove a user from a chatroom */
    public void removeChatroomUser(String _roomname, String _username) {
       if(!this.theClient.isConnected)
	   return;
	
       this.theClient.sendMessage("std::removeChatRoomUser(\"" + _roomname + "\", \"" + _username + ")", null, "command", null, "rmchatuser01");
    }
    
    /** Opens a chat-window for the _first_ selected user */
    public void openChatWindow() {
       this.WriteMessageActionPerformed(null);
    }

    /** Opens the Mail Window */
    private void WriteMailActionPerformed(java.awt.event.ActionEvent evt) {
       int ind[] = this.jListMembers.getSelectedIndices();
       if(ind.length <= 0)
	  return;

       // Create "to:" String
       String to = "";
       String recs = "";
       for( int i = 0; i < ind.length; i++ ) {
	  to += ("- " + ((JTalkerClient.MemberData)this.theClient.allMembers.get(ind[i])).short_name + "\n");	  
	  recs += ((JTalkerClient.MemberData)this.theClient.allMembers.get(ind[i])).short_name + ";;";	  
       }
       
       String retVal = JOptionPane.showInputDialog("Message to: \n" + to);
       if(retVal == null)
	  return;

       retVal = "<i>[To: " + recs.replaceAll(";;",", ") + "]</i><br>" + retVal;

       // make HTML-compatible
       /*retVal = JTalkerClientProtocol.toHTMLString(retVal);
       retVal = retVal.replaceAll("&","&amp;");
       retVal = retVal.replaceAll("<","&lt;");
       retVal = retVal.replaceAll(">","&gt;");*/
       
       this.theClient.sendMessage(retVal, recs);
       return;
    }

    /** Gets selected User */
    public JTalkerClient.MemberData getSelectedUser() {
       int ind = this.jListMembers.getSelectedIndex();
       if(ind == -1)
	  return null;

       try {
	  return (JTalkerClient.MemberData)this.theClient.allMembers.get(ind); 
       } catch (Exception _ex) {
	  return null;
       }
    }

    /** Refresh List */
    public void refreshActionPerformed() {
        // Refreshes the list
        
        if(this.theClient.STATE == JTalkerClient.STATE_OFFLINE)
            this.connectionEstablished(false);
        else if(this.theClient.STATE == JTalkerClient.STATE_CONNECTED)
            this.connectionEstablished(true);

	if(this.isConnected) {
	   /*if(!this.theClient.lookUp()) {
	      System.out.println("*** Server doesn't response!");
	      javax.swing.JOptionPane.showMessageDialog(null, 
						      "Server doesn't response! Check connection!", 
						      "Server doesn't response", 
						      javax.swing.JOptionPane.ERROR_MESSAGE);
	      if(this.isConnected)
		  this.connectActionPerformed(null);
	      return;
	   }*/
	      
	   //this.jListMembers.updateUI();
	   this.theClient.memberList.propertyChanged();
	}
	else
	   this.jLabel2.setText("You are not connected! Connect first.");
    } 
   
    /** Toggle users status */
    private void statusActionPerformed(java.awt.event.ActionEvent evt) {
       if(this.jToggleButtonStatus.isSelected()) {
	  this.theClient.userStatus = "busy";	  
       }
       else {
	  this.theClient.userStatus = "normal";	  
       }

       if(this.isConnected) {
	  this.theClient.lookUp();
	  this.theClient.memberList.propertyChanged();
       }
    }

    /** Shows PopUp for a user*/
    private void maybeShowPopup(java.awt.event.MouseEvent _e) {    	
        if(this.userPopup == null) {
	   // Create PopUp
	   this.userPopup = new JTalkerClientFrontPopUp(this);
	}
	
    	if(_e.isPopupTrigger()){
	    if(this.jListMembers.getFirstVisibleIndex() == -1)	
	       return;
		
	    this.jListMembers.setSelectedIndex(this.jListMembers.locationToIndex(_e.getPoint()));
	    this.userPopup.show(_e.getComponent(), _e.getX(), _e.getY());
    	}
    }

    /** Notify by incomming of new messages */
    private void notifyOnNewMessage(boolean _enable, String _text) {
       if(_enable) {
	  // Enable choosen notificator
	  switch(this.theClient.newMailNotificationType) {
	    case 0: break;
	    case 1: this.toFront(); break;
	    case 2: 
		    if(this.newMessageNotificator == null) {
		       this.newMessageNotificator = new NotificationWindow(this);
		       this.newMessageNotificator.setPosition(NotificationWindow.BOTTOM_RIGHT);
		    }
		    this.newMessageNotificator.setMemberName(_text);
		    this.newMessageNotificator.setVisible(true);
		    break;
	    case 3: Toolkit.getDefaultToolkit().beep();      
	  }
       } else {
	  // Disable notification	 
          if(this.newMessageNotificator != null)
	    this.newMessageNotificator.setVisible(false);
       }
    }

    /** Rebuild all Plugin-Buttons in the Toolbar */
    public void updatePluginShortcuts() {
        String [] allEmbPlugins = this.theClient.getPluginShortcuts();
        JTalkerClientPlugInInterface tmpPlugin;
        this.jPanelPlugIns.removeAll();

        for( int i = 0; i < allEmbPlugins.length; i++ ) {
            tmpPlugin = this.myPluginLoader.getPluginByName(allEmbPlugins[i]);
            if(tmpPlugin != null) {
                javax.swing.JButton jb = new javax.swing.JButton();
                jb.setName(tmpPlugin.getClass().getName());
                jb.setToolTipText("Plugin: " + tmpPlugin.getName());
                jb.setMargin(new java.awt.Insets(2, 2, 2, 2));
                jb.setPreferredSize(new java.awt.Dimension(48, 32));
                if(tmpPlugin.getIcon() == null)
                    jb.setText(tmpPlugin.getName());
                else
                    jb.setIcon(tmpPlugin.getIcon());
                jb.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        // TODO: search for a workaround!
                        openPluginMainGUIFor(((JButton)evt.getSource()).getName());
                    }
                });
                this.jPanelPlugIns.add(jb);
            }
        }
    }
    
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
       if(this.isConnected)
	 this.theClient.closeConnection();
       System.exit(0);
    }//GEN-LAST:event_exitForm
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               // Init JTalkerClient
               JTalkerClient jtc = new JTalkerClient();
       
               // Set Look and Feel
               try {
                UIManager.setLookAndFeel(jtc.guiPlaf);    
               } catch (Exception e) {
                  System.err.println("*** Can't set Look'n'Feel. Use default.");
               }
           
               //new JTalkerClientFront(jtc).show();
               new JTalkerClientFront(jtc).setVisible(true);
            }
        });
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem jMenuItemConnect;
    private javax.swing.JMenuItem jMenuItemCommand;
    private javax.swing.JMenuItem jMenuItemChatroom;
    //private javax.swing.JComboBox jComboBoxRefresh;
    private javax.swing.JPanel jPanelStatus;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItemBusy;
    private javax.swing.JButton jButtonConnect;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonConfig;
    private javax.swing.JMenuItem jMenuItemAccount;
    private javax.swing.JMenuItem jMenuItemAbout;
    private javax.swing.JMenu jMenuStatus;
    private javax.swing.JMenu jMenuPlugins;
    private javax.swing.JMenu jMenuAbout;
    private javax.swing.JPanel jPanelToolsT;
    private javax.swing.JScrollPane jScrollPaneMembers;
    private javax.swing.JList jListMembers;
    private javax.swing.JPanel jPanelMamberList;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPanel jPanelToolsR;
    private javax.swing.JButton jButtonOpen;
    private javax.swing.JButton jButtonMail;
    private javax.swing.JMenuItem jMenuItemSettings;
    private javax.swing.JMenuBar jMenuBarMain;
    private javax.swing.JToggleButton jToggleButtonStatus;
    private javax.swing.JMenuItem jMenuItemClose;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JButton jButtonReload;
    private javax.swing.JMenu jMenuServer;
    // End of variables declaration//GEN-END:variables
    public boolean isConnected = false;
    public boolean isLogedIn = false;
    public JTalkerClient theClient;
    private ClassLoader cl;
    private JTalkerFrontSettings mySettings = null;
    private JTalkerFrontCommand myCommandDialog = null;
    public boolean enableNotification = false; // Make some actions on new message ;-)
    private JTalkerClientFrontPopUp userPopup = null;
    private NotificationWindow newMessageNotificator = null;
    private JTalkerClientPluginLoader myPluginLoader = null;
    public JTalkerClientPluginsInfo myPluginsInfoDialog = null;
    private ImageIcon connectPlainText = null;
    private ImageIcon connectEncrypted = null;
    
    private javax.swing.JPanel jPanelPlugIns;


    /** This class represents a List Row */
    class MyCellRenderer extends JLabel implements ListCellRenderer {
     private ImageIcon userIcon = new ImageIcon(cl.getResource("icons/user.png"));
     private ImageIcon userMeIcon = new ImageIcon(cl.getResource("icons/me.png"));
     private ImageIcon userbIcon = new ImageIcon(cl.getResource("icons/user_busy.png"));
     private ImageIcon chatroomIcon = new ImageIcon(cl.getResource("icons/chatroom.png"));
     private ImageIcon newMailIcon = new ImageIcon(cl.getResource("icons/new_mail.png"));
     private JTalkerClientFront parent = null;

     public MyCellRenderer(JTalkerClientFront _parent) {
	this.parent = _parent;
     }

     // This is the only method defined by ListCellRenderer.
     // We just reconfigure the JLabel each time we're called.

     public Component getListCellRendererComponent(
       JList _list,
       Object _value,            // value to display
       int _index,               // cell index
       boolean _isSelected,      // is the cell selected
       boolean _cellHasFocus)    // the list and the cell have the focus
     {
	 if(_value == null)
	    return null;
	 
         String tmpName = ((JTalkerClient.MemberData)_value).name;
         this.setText(tmpName.replaceAll(" AT ", " @ "));
	 
	 if (((JTalkerClient.MemberData)_value).hasNewMessage) {
	    if(!((JTalkerClient.MemberData)_value).name.equals(this.parent.theClient.userName)) {
	       this.setIcon(this.newMailIcon);
	       
	       // Get focus, only if no chat window open
	       if(!((JTalkerClient.MemberData)_value).isChatWindowOpen()) {
		  this.parent.notifyOnNewMessage(true, tmpName);		  
	       }
	       
	    } else
	       this.setIcon(this.userMeIcon);
	 }
	 else if(((JTalkerClient.MemberData)_value).status.equals("busy"))
	    this.setIcon(this.userbIcon);
	 else if(((JTalkerClient.MemberData)_value).type.equals(JTalkerParser.USER_TYPE_CHATROOM))
	    this.setIcon(this.chatroomIcon);
	 else {
	    this.parent.notifyOnNewMessage(false, null);
	    if(((JTalkerClient.MemberData)_value).short_name.equals(this.parent.theClient.userName))
	       this.setIcon(this.userMeIcon);
	    else
	       this.setIcon(this.userIcon);
	 }
	 
         if (_isSelected) {
             this.setBackground(_list.getSelectionBackground());
             this.setForeground(_list.getSelectionForeground());
         }
         else {
             this.setBackground(_list.getBackground());
             this.setForeground(_list.getForeground());
         }
         
	 this.setEnabled(_list.isEnabled());
         this.setFont(_list.getFont());
         this.setOpaque(true);

	 if(!((JTalkerClient.MemberData)_value).isConnected()) {
	    // Mark offline user
	    this.setEnabled(false);
	 }
	 
         return this;
     }
    }

    /** Class for asynchron updating the Window */
    public class UpdateTimer extends Thread {
       private JTalkerClientFront parent = null;
       
       public UpdateTimer (JTalkerClientFront _parent) {
	  this.parent = _parent;
       }
       
       public void run() {
	  while(true) {    
	     this.parent.refreshActionPerformed();
	     
	     try {
		// Reload every 2 sec
		this.sleep(1000);
	     } catch (Exception e) {} 
	  }
	  
       }
    }

    /** This class represents an plugin menu item */
    public class PlugInMenuItem extends javax.swing.JMenuItem {
        public String pluginClass = null;
        public int type = 0; // 0: mainGui, 1: Settings

        public PlugInMenuItem (String _pluginClass, int _type) {
            super();
            this.pluginClass = _pluginClass;
            this.type = _type;
        }
    }
       
}
